package niuke;

/**
 * description:
 * author:张腾
 * date:2021-07-24
 */

/**
 * 给定两个字符串str1和str2,输出两个字符串的最长公共子串
 * 题目保证str1和str2的最长公共子串存在且唯一。
 */
public class NC127 {
    public String LCS (String str1, String str2) {
        // write code here
        int maxLength = 0;
        int maxLstIndex = 0;
        int[][] dp = new int[str1.length()+1][str2.length()+1];
        for (int i = 0; i < str1.length(); i++) {
            for (int j = 0; j < str2.length(); j++) {
                if (str1.charAt(i)==str2.charAt(j)) {
                    dp[i+1][j+1] = dp[i][j]+1;
                    if (dp[i+1][j+1]>maxLength){
                        maxLength = dp[i+1][j+1];
                        maxLstIndex = i;
                    }
                } else{
                    dp[i+1][j+1] = 0;
                }

            }
        }
        return str1.substring(maxLstIndex-maxLength+1,maxLstIndex+1);
    }
}
